package com.scs.application.core.pdf.handler;

import com.scs.application.core.utils.DateUtils;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import org.apache.logging.log4j.util.Strings;

import java.util.Date;

/**
 * @description:
 */
public class HeaderHandler implements IEventHandler {

    protected PdfFormXObject template;

    protected PdfFont font;

    protected int totalPage;

    protected String strHeadDate;

    public HeaderHandler(PdfFormXObject template, PdfFont font, int totalPage, String strHeadDate) {
        this.template = template;
        this.font = font;
        this.totalPage = totalPage;
        this.strHeadDate = strHeadDate;
    }


    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfPage page = docEvent.getPage();

        int pageNum = docEvent.getDocument().getPageNumber(page);

        PdfCanvas canvas = new PdfCanvas(page);

        float width = page.getPageSize().getWidth();
        float height = page.getPageSize().getHeight();

        canvas.beginText()
                .setFontAndSize(font, 10)
                .beginMarkedContent(PdfName.Artifact)
                .moveText(width - 70, height - 20)
                .showText(String.format("第%d页/共%d页", pageNum, totalPage))
                .endText()
                .stroke()
                .addXObject(template, 0, 0)
                .endMarkedContent()
                .release();

        new PdfCanvas(page)
                .beginText()
                .moveText(20, height - 20)
                .setFontAndSize(font, 10)
                .beginMarkedContent(PdfName.Artifact)
                .showText(Strings.isBlank(strHeadDate) ? DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") : strHeadDate)
                .endText()
                .stroke()
                .addXObject(template, 0, 0)
                .endMarkedContent()
                .release();
    }
}

